#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

static int shell(char *buffer, unsigned int max, const char *cmd)
{
    FILE *pipe;
    unsigned int len, max_len = max - 1;

    pipe = popen(cmd, "r");
    if (NULL == pipe)
    {
        sprintf(buffer, "create shell cmd pipe:::%s", strerror(errno));
        printf("%s", buffer);
        return -1;
    }

    while (1)
    {
        len = strlen(buffer);
        if (len >= max_len)
            break;

        if (NULL == fgets(&buffer[len], max - len, pipe))
            break;
    }

    printf("# %s\n", cmd);
    printf("%s\n", buffer);

    pclose(pipe);
    return 0;
}

int main(int argc, char const *argv[])
{
    char buffer[4096] = {0};

    shell(buffer, sizeof(buffer), "pwd");
    return 0;
}
